package com.liugh.util;

import cn.hutool.core.io.FileUtil;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author liugh
 * @since on 2018/5/8.
 */
public class LiughFileUtil {

    private static final Logger logger = LoggerFactory.getLogger(LiughFileUtil.class);

    /**
     * File类型的文件转换为MultipartFile的文件
     * @return
     */
    public static MultipartFile fileToMulFile(File file) throws IOException {
        try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file))) {
            return new MockMultipartFile(file.getName(), file.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), bufferedInputStream);
        }
    }

    /**
     * 从url中下载文件,返回文件的存储位置
     */
    public static String getFileFromUrl(String fileUrl,String storePath,String fileName) throws IOException {
        URL url = new URL(fileUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(3000);
        connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36");
        FileUtil.mkdir(storePath);
        File file = new File(storePath + fileName);
        byte[] bytes = new byte[1024];
        int len;
        try (BufferedInputStream InputStream = new BufferedInputStream(connection.getInputStream());
             BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) {
            while ((len = InputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
        }
        connection.disconnect();
        return storePath + fileName;
    }
}
